package com.egao.api.base;

import com.egao.common.system.entity.User;
import com.egao.common.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.util.SubjectUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * ApiController基类
 * Created by wangfan on 2019-05-06 上午 9:26.
 */
public class BaseApiController {

    @Autowired
    protected UserService userService;

    /**
     * 获取当前登录的userId
     */
    public String getLoginUserId(HttpServletRequest request) {
        Token token = getLoginToken(request);
        return token == null ? "" : token.getUserId();
    }

    /**
     * 获取当前登录的user
     */
    public User getLoginUser(HttpServletRequest request) {
        Token token = getLoginToken(request);
//        Token token = SubjectUtil.parseToken(request);
        if (token != null) return userService.getById(new User(Integer.valueOf(token.getUserId())));
        return null;
    }

    /**
     * 获取当前的token
     */
    public Token getLoginToken(HttpServletRequest request) {
        return SubjectUtil.getToken(request);
    }

    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //        String uri = request.getRequestURI();//返回请求行中的资源名称
//            String url = request.getRequestURL().toString();//获得客户端发送请求的完整url
//           String ip = request.getRemoteAddr();//返回发出请求的IP地址
//         String params = request.getQueryString();//返回请求行中的参数部分
//           String host=request.getRemoteHost();//返回发出请求的客户机的主机名
//         int port =request.getRemotePort();//返回发出请求的客户机的端口号。
//         System.out.println(ip);
//            System.out.println(url);
//           System.out.println(uri);
//         System.out.println(params);
//         System.out.println(host);
//          System.out.println(port);
        return ip;
    }
}
